package baiqitun.stupro.security.core.service.support;

import baiqitun.stupro.common.enums.BooleanEnum;
import baiqitun.stupro.security.entity.SysRole;
import baiqitun.stupro.security.entity.SysUser;
import baiqitun.stupro.security.service.SysRolePermissionService;
import baiqitun.stupro.security.service.SysUserRoleService;
import baiqitun.stupro.security.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;

import java.util.LinkedList;
import java.util.List;

/**
 * 查找用户业务
 * @author kedaji
 */
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Cacheable("user")
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查找用户信息
        SysUser user = sysUserService.getUserByUsername(username);
        if (user == null){
            throw new UsernameNotFoundException(username);
        }
        // 查找用户的角色权限
        List<SysRole> roles = sysUserRoleService.listRoleByUserId(user.getId());
        return assembleUser(user, roles);
    }

    /**
     * 将用户信息与权限信息进行组合
     * @param user 用户信息
     * @param roles 角色权限列表
     * @return 待处理的认证用户
     */
    private User assembleUser(SysUser user, List<SysRole> roles){
        String username = user.getUsername();
        String password = user.getPassword();
        boolean enabled = user.getDeleted().equals(BooleanEnum.FALSE.getValue());
        boolean locked = user.getEnabled().equals(BooleanEnum.TRUE.getValue());

        List<GrantedAuthority> grantedAuthorities = new LinkedList<>();
        for (SysRole role: roles){
            grantedAuthorities.add(new SimpleGrantedAuthority(role.getCode()));
        }
        return new User(username, password,
                enabled, true, true, locked,
                grantedAuthorities);
    }
}
